CC = $(CROSS)g++
AR = $(CROSS)ar rc
SR = $(CROSS)g++ -shared
LD = $(CROSS)ld 

TARGET   := libtestbench
BUILDIN  := build-in.o

SUBDIRS = source library

SRC_FILES := $(wildcard *.cpp)
OBJ_FILES := $(SRC_FILES:.cpp=.o)

SUB_FILES := $(addsuffix /$(BUILDIN),$(SUBDIRS))
EXT_FILES := $(PWD)/TestBench/library/libpcap/lib/$(CROSS)libpcap.a
EXT_FILES += $(PWD)/out/third/lib/libtermcap.a
EXT_FILES += $(PWD)/out/third/lib/libreadline.a
EXT_FILES += $(PWD)/out/third/lib/libhistory.a

subdir     := $(addprefix build_,$(SUBDIRS) )
clean_dirs := $(addprefix clean_,$(SUBDIRS) )

#WARNINGS = -Wall -Wextra -Werror -Wfatal-errors
#WARNINGS = -Wall
INCLUDE_DIRS = -I$(PWD)/TestBench \
               -I$(PWD)/TestBench/include \
               -I$(PWD)/TestBench/library/libavi \
               -I$(PWD)/TestBench/library/libpcap/include \
               -I$(PWD)/out/third/include/

CC_FLAGS := $(WARNINGS) $(INCLUDE_DIRS)
CC_FLAGS +=  -O2 -fPIC
CFLAGS   += $(CC_FLAGS)

LD_FLAGS += -L./ -L$(PWD)/out/third/lib -ltermcap -lreadline -lhistory

export PWD
export CROSS
export CC_FLAGS
export BUILDIN

# default rule
default: all

# non-phony targets
$(TARGET): $(OBJ_FILES)
	@echo "LD  $(TARGET)"
	$(LD) -o $(TARGET).o -r $(OBJ_FILES) $(SUB_FILES) $(EXT_FILES) $(LD_FLAGS)
	$(AR)    $(TARGET).a  $(TARGET).o
	$(SR) -o $(TARGET).so $(TARGET).o
	@cp $(TARGET).o  $(OUTDIR)
	@cp $(TARGET).a  $(OUTDIR)
	@cp $(TARGET).so $(OUTDIR)

$(OBJ_FILES): %.o:%.cpp
	$(CP) $(CC_FLAGS) -c -o $@ $<

$(SUBDIRS):
	@echo "CROSS = $(CROSS)"
	make -C $@

$(subdir):
	@echo "CC  $@"
	@echo "CROSS = $(CROSS)"
	$(MAKE) -C $(patsubst build_%,%,$@)

$(clean_dirs):
	$(MAKE) -C $(patsubst clean_%,%,$@) clean

# phony rules
.PHONY: all 
all: $(subdir) $(TARGET)

.PHONY: clean
clean: $(clean_dirs)
	rm -f *.o